//
//  YLYBillMapViewController.m
//  iEasyBill
//
//  Created by student on 14-6-4.
//  Copyright (c) 2014年 com.yly16. All rights reserved.
//

#import "YLYBillMapViewController.h"
#import <MapKit/MapKit.h>

@interface YLYBillMapViewController ()<MKMapViewDelegate,CLLocationManagerDelegate>
@property (weak, nonatomic) IBOutlet MKMapView *mapView;

@end

@implementation YLYBillMapViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    self.mapView.delegate = self;
    
    NSDate *starDate = [self getBeginAndEndWithDate:[NSDate date] andIdBegin:YES];
    NSDate *endDate = [self getBeginAndEndWithDate:[NSDate date] andIdBegin:NO];
    self.monthbillList = [[DatabaseManager shareManager]showBillByDate:starDate toDate:endDate toType:nil];
    self.monthbillList = [self getlocationArray:self.monthbillList];
    
    NSMutableArray *ilist = [[NSMutableArray alloc]init];
    for (int i =0; i< self.monthbillList.count ; i++) {
        YLYPinView *pinView = [[YLYPinView alloc]init];
        NSDictionary *dic = [self.monthbillList objectAtIndex:i];
        CGFloat la = [[dic objectForKey:@"billlatitude"] floatValue];
        CGFloat lo = [[dic objectForKey:@"billlongitude"] floatValue];
        pinView.coordinate = CLLocationCoordinate2DMake(la, lo);
        pinView.title = [NSString stringWithFormat:@"%d笔账单",[[dic objectForKey:@"list"] count]];
        [ilist addObject:pinView];
    }
    float maxLat,minLat,maxLon,minLon;
    YLYPinView *firstSight = [ilist firstObject];
    maxLat = firstSight.coordinate.latitude;
    minLat = maxLat;
    maxLon = firstSight.coordinate.longitude;
    minLon = maxLon;
    for (YLYPinView *oneSight in ilist) {
        if (oneSight.coordinate.latitude > maxLat) {
            maxLat = oneSight.coordinate.latitude;
        }
        if (oneSight.coordinate.latitude < minLat) {
            minLat = oneSight.coordinate.latitude;
        }
        if (oneSight.coordinate.longitude > maxLon) {
            maxLon = oneSight.coordinate.longitude;
        }
        if (oneSight.coordinate.longitude < minLon) {
            minLon = oneSight.coordinate.longitude;
        }
    }
    
    MKCoordinateSpan span = MKCoordinateSpanMake(maxLat-minLat+0.5, maxLon-minLon+0.5);
    CLLocationCoordinate2D coord= CLLocationCoordinate2DMake(0.5*(maxLat+minLat), 0.5*(maxLon+minLon));
    MKCoordinateRegion region = MKCoordinateRegionMake(coord, span);
    self.mapView.region = region;
    [self.mapView addAnnotations:ilist];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//TODO:根据一个date得到这个date的一个月的结束日期
- (NSDate *)getBeginAndEndWithDate:(NSDate *)date andIdBegin:(BOOL)isbegin{
    NSDate *newDate = date;
    double interval = 0;
    NSDate *beginDate = nil;
    NSDate *endDate = nil;
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    [calendar setFirstWeekday:2];//设定周一为周首日
    BOOL ok;
    ok = [calendar rangeOfUnit:NSMonthCalendarUnit startDate:&beginDate interval:&interval forDate:newDate];
    //分别修改为 NSDayCalendarUnit NSWeekCalendarUnit NSYearCalendarUnit 可查年、月、周开始结束 “某个时间点”所在的“单元”的起始时间，以及起始时间距离“某个时间点”的时差（单位秒）
    if (ok) {
        endDate = [beginDate dateByAddingTimeInterval:interval-1];
    }else {
        return nil;
    }
    /*
     NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
     [myDateFormatter setDateFormat:@"MM.dd"];
     NSString *beginString = [myDateFormatter stringFromDate:beginDate];
     NSString *endString = [myDateFormatter stringFromDate:endDate];
     
     return [NSString stringWithFormat:@"%@-%@",beginString,endString];
     */
    if (isbegin == YES) {
        return beginDate;
    }
    return endDate;
}
-(NSMutableArray*)getlocationArray:(NSMutableArray*)array{
    NSMutableArray *rootList = [[NSMutableArray alloc]init];
    
    for (int i = 0;i<array.count;i++) {
        NSMutableDictionary *rootDic = [[NSMutableDictionary alloc]init];
        iBill *aBill = [array objectAtIndex:i];
        NSMutableArray *list = [[NSMutableArray alloc]init];
        if (rootList.count == 0) {
            [list addObject:aBill];
            [rootDic setObject:aBill.billlatitude forKey:@"billlatitude"];
            [rootDic setObject:aBill.billlongitude forKey:@"billlongitude"];
            [rootDic setObject:list forKey:@"list"];
            [rootList addObject:rootDic];
        }
        else{
            BOOL isOk = NO;
            //NSMutableArray *temp = [rootList objectAtIndex:i-1];
            for (NSMutableDictionary *temp in rootList) {
                for (iBill *OldBill in [temp objectForKey:@"list"]) {
                    if (aBill.billlatitude.floatValue == OldBill.billlatitude.floatValue && aBill.billlongitude.floatValue == OldBill.billlongitude.floatValue) {
                        list = [temp objectForKey:@"list"];
                        [list addObject:aBill];
                        [temp setObject:list forKey:@"list"];
                        isOk = YES;
                        break;
                    }
                }
            }
            if (isOk == NO) {
                [list addObject:aBill];
                [rootDic setObject:aBill.billlatitude forKey:@"billlatitude"];
                [rootDic setObject:aBill.billlongitude forKey:@"billlongitude"];
                [rootDic setObject:list forKey:@"list"];
                [rootList addObject:rootDic];
            }
        }
        
    }
    return rootList;
}
@end
